package
{
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.external.ExternalInterface;
	import flash.system.Security;
	import flash.system.SecurityDomain;
	import flash.text.TextField;
	import flash.utils.Timer;
	
	import org.flexunit.runner.manipulation.filters.AbstractFilter;
	import org.hyOnline.ebay.ClientCollector;
	import org.hyOnline.ebay.JsForHfash;
	import org.hyOnline.ebay.XhrForEbay;
	
	public class HfashEbayHelper extends Sprite
	{
		private var jsReadyTimer:Timer;
		private var textField:TextField;
		private var jsCheckTimes:int=0;
		private var jsReady:Boolean = false;
		private var xhr:XhrForEbay;
		public function HfashEbayHelper()
		{
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			Security.allowDomain('*');
			graphics.beginFill(0xff0000);
			graphics.drawCircle(0,0,10);
			graphics.endFill();
			setupOutput();
			init();
		}
		private function init(e:Event = null):void{
			if(!JsForHfash.is_Ready()){
				if(jsReadyTimer == null){
					jsReadyTimer = new Timer(500,1);
					jsReadyTimer.addEventListener(TimerEvent.TIMER,init);
				}
				jsReadyTimer.reset();
				jsReadyTimer.start();
			}else{
				jsReady=true;
				xhr = new XhrForEbay(JsForHfash.getProductId(),JsForHfash.getProductType());
				setupExternalInterface();
				JsForHfash.setupPage();
				new ClientCollector().doCollect();
			}
		}
		private function setupExternalInterface():void{
			if(ExternalInterface.available){
				ExternalInterface.addCallback('println',println);
				ExternalInterface.addCallback('loadJSON',loadJSON);
				graphics.beginFill(0x00ffff);
				graphics.drawCircle(0,0,10);
				graphics.endFill();
			}
		}
		private function setupOutput():void{
			textField = new TextField();
			addChild(textField);
			textField.x =10;
			textField.y =0;
			textField.width=100;
			textField.height=100;
		}
		public function loadJSON(params:Object=null):void{
			xhr.loadJSON(params);
		}
		public function print(text:String=""):void{
			textField.appendText(text);
		}
		public function println(text:String=""):void{
			textField.appendText(text+"\n");
		}
	}
}